package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FocusUserApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.server.utils.UserHolder;
import org.apache.commons.io.FileUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class VideoService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference
    private VideoApi videoApi;
    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private FocusUserApi focusUserApi;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @CacheEvict(value = "videoList",allEntries = true)
    public ResponseEntity uploadVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws Exception {
//        1、图片上传到阿里云
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
//        2、小视频存到fastDfs中
//         adgsad.avi
//         lkjasegfasd.sfds.adgsad.mp4
        String videoFilename = videoFile.getOriginalFilename();
//        截取文件名中最后一个点以后的内容
        String extName = videoFilename.substring(videoFilename.lastIndexOf(".")+1);
        StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(),videoFile.getSize(), extName, null);
        String videoUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
//        3、构建Video对象
        Video video  = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我怎么这么好看");
//        4、调用dubbo的保存小视频的方法
        videoApi.save(video);

        return ResponseEntity.ok(null);

    }
//    videoList:1_10
//    videoList:2_10
//    videoList:3_10

    @Cacheable(value = "videoList",key="#page + '_' +  #pagesize")
    public PageResult queryVideoList(Integer page, Integer pagesize) {
//        TODO 后面会改成从大数据推荐产生的表中查询
//        从video表查询
       PageResult pageResult = videoApi.queryVideoList(page,pagesize);
        System.out.println("数据是从mongo数据库中获取的");
       List<Video> items = (List<Video>) pageResult.getItems();
//       把Video转成 VideoVo
        List<VideoVo> list = new ArrayList<>();
        for (Video video : items) {
            VideoVo videoVo = new VideoVo();
            UserInfo userInfo = userInfoApi.findById(video.getUserId());
//            把 video+userInfo ---》videoVo
            BeanUtils.copyProperties(video,videoVo);

            videoVo.setId(video.getId().toString());
            videoVo.setCover(video.getPicUrl());
            videoVo.setSignature(video.getText());

            videoVo.setHasLiked(0); //是否点赞
            if(redisTemplate.hasKey("focus_user_"+UserHolder.getUserId()+"_"+video.getUserId())){
                videoVo.setHasFocus(1); //关注博主
            }else{
                videoVo.setHasFocus(0); //没有关注博主
            }


            BeanUtils.copyProperties(userInfo,videoVo);
            videoVo.setUserId(userInfo.getId());
            list.add(videoVo);
        }

        pageResult.setItems(list);
        return pageResult;
    }

//    关注视频博主
@CacheEvict(value = "videoList",allEntries = true)
    public ResponseEntity userFocus(Long focusUserId) {
//        保存 FocusUser
        focusUserApi.save(UserHolder.getUserId(),focusUserId);

        redisTemplate.boundValueOps("focus_user_"+UserHolder.getUserId()+"_"+focusUserId).set("");

        return ResponseEntity.ok(null);

    }
//    当前登录人取消关注视频博主
@CacheEvict(value = "videoList",allEntries = true)
    public ResponseEntity userUnFocus(Long focusUserId) {
        focusUserApi.delete(UserHolder.getUserId(),focusUserId);
        redisTemplate.delete("focus_user_"+UserHolder.getUserId()+"_"+focusUserId);
        return ResponseEntity.ok(null);
    }


}
